<template>
  <div class="device-template">
    <div class="page-header">
      <h2>设备模板管理</h2>
      <p>管理设备导入模板，建立设备数据库</p>
    </div>

    <!-- 选择操作页面 -->
    <el-card class="main-card" v-if="currentStep === 'main'">
      <template #header>
        <h3>设备模板管理</h3>
      </template>

      <div class="operation-selection">
        <div class="operation-card-container">
          <!-- 导入模板选项 -->
          <el-card class="operation-card" shadow="hover" @click="showUploadDialog">
            <div class="operation-content">
              <el-icon size="48" color="#409EFF"><UploadFilled /></el-icon>
              <h4>导入新模板</h4>
              <p>上传Excel设备模板文件，建立新的设备数据库</p>
            </div>
          </el-card>

          <!-- 使用历史数据选项 -->
          <el-card class="operation-card" shadow="hover" @click="viewHistoryData">
            <div class="operation-content">
              <el-icon size="48" color="#67C23A"><View /></el-icon>
              <h4>查看历史数据</h4>
              <p>查看已导入的设备模板数据，或了解如何开始导入</p>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 历史数据展示页面 -->
    <el-card class="main-card" v-if="currentStep === 'history'">
      <template #header>
        <div class="card-header">
          <h3>历史设备数据</h3>
          <div class="header-actions">
            <el-button @click="currentStep = 'main'">返回</el-button>
            <el-button v-if="hasHistoryData" type="primary" @click="showUploadDialog">
              重新导入模板
            </el-button>
            <el-button
              type="success"
              :disabled="!hasHistoryData"
              @click="$router.push('/startup-plan')"
            >
              使用当前模板
            </el-button>
          </div>
        </div>
      </template>

      受令单位（{{ commandingUnits.length }}个）
      <el-input
        v-model="searchCommandingUnit"
        placeholder="搜索受令单位"
        style="width: 300px"
        clearable
      />
      <div class="search-bar"></div>
      <!-- <el-divider border-style="dashed" ></el-divider> -->
      <div class="flex gap-0 overflow-x-auto">
        <el-tag type="primary" v-for="unit in filteredCommandingUnity">{{
          unit.unitName
        }}</el-tag>
      </div>
      <el-divider />

      <!-- 无历史数据提示 -->
      <div class="no-data-hint" v-if="!hasHistoryData">
        <el-empty description="暂无历史设备模板数据" :image-size="120">
          <template #description>
            <div class="empty-description">
              <h4>暂无历史设备模板数据</h4>
              <p>系统中还没有导入过设备模板，无法查看历史数据</p>
              <p>请先上传《启动方案设备导入模板》Excel文件来建立设备数据库</p>
              <p class="empty-tip">支持 .xlsx 格式，文件大小不超过 10MB</p>
            </div>
          </template>
          <div class="empty-actions">
            <el-button type="primary" size="large" @click="showUploadDialog">
              <el-icon><UploadFilled /></el-icon>
              立即上传设备模板
            </el-button>
          </div>
        </el-empty>
      </div>

      <!-- 数据统计信息 -->
      <!-- 按厂站分组展示设备数据 -->
      <div v-if="hasHistoryData" class="history-data">
        设备总数（{{ devices.length }}个）
        <el-input
          v-model="searchDeviceText"
          placeholder="搜索设备"
          style="width: 300px"
          clearable
        />
        <div class="search-bar"></div>

        <el-collapse accordion key="main" class="category-group">
          <div
            v-for="group in filteredDevices"
            :key="group.deviceCategory"
            style="margin-left: 10px; margin-right: 10px"
          >
            <!-- 可展开的表格 -->
            <el-collapse-item
              :key="group.deviceCategory"
              :title="group.deviceCategory"
              :name="group.deviceCategory"
            >
              <el-table
                :data="group.categoryGroup"
                size="small"
                stripe
                border
                :show-header="true"
                class="device-table"
              >
                <el-table-column prop="voltageLevel" label="电压等级" width="100" />
                <el-table-column prop="deviceName" label="设备名称" />
                <el-table-column prop="deviceCode" label="设备编号" />
                <el-table-column prop="deviceType" label="设备类型" />
                <el-table-column
                  prop="deviceDoubleCode"
                  label="设备双编"
                  min-width="200"
                />
                <el-table-column prop="updatedTime" label="更新时间" width="180">
                  <template #default="scope">
                    {{ formatTime(scope.row.updatedTime) }}
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </div>
        </el-collapse>
      </div>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="重新导入设备模板"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="upload-dialog-content">
        <el-alert
          v-if="do_clear"
          title="清空导入"
          type="warning"
          :closable="false"
          show-icon
        >
          将清空历史数据，以新导入文档设备和受令单位作为模板（推荐）
        </el-alert>
        <el-alert
          v-if="!do_clear"
          title="新增导入"
          type="warning"
          :closable="false"
          show-icon
        >
          基于原有设备和受令单位，导入新增数据，过滤已有设备模板
          （如果想要修改项目，请选择清空导入，建议同时《维护完整启动方案设备导入模板》）
        </el-alert>
        <el-switch
          v-model="do_clear"
          class="mb-2"
          active-text="清空导入"
          inactive-text="新增导入"
        />
        <br />

        <div class="upload-area" :class="{ 'mt-20': hasHistoryData }">
          <el-upload
            drag
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept=".xlsx"
            :limit="1"
            class="upload-dragger"
          >
            <el-icon class="upload-icon"><UploadFilled /></el-icon>
            <div class="upload-text">
              <p>拖拽《启动方案设备导入模板》.xlsx文件到此处</p>
              <p class="upload-tip">支持 .xlsx 格式，文件大小不超过 10MB</p>
            </div>
          </el-upload>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" :disabled="!fileList.length" @click="uploadTemplate">
            开始导入
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入结果对话框 -->
    <el-dialog
      v-model="resultDialogVisible"
      title="导入结果"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="result-summary" v-if="importResult">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="文档提交数（受令单位+设备数）">
            <span class="result-number"
              >{{ importResult.totalCommandingUnits + importResult.totalDevices }}({{
                importResult.totalCommandingUnits
              }}+{{ importResult.totalDevices }})</span
            >
          </el-descriptions-item>
          <el-descriptions-item label="去重后">
            <span class="result-number"
              >{{ importResult.uniqueCommandingUnits + importResult.uniqueDevices }}({{
                importResult.uniqueCommandingUnits
              }}+{{ importResult.uniqueDevices }})</span
            >
          </el-descriptions-item>
          <el-descriptions-item label="成功记录数">
            <span class="result-number success">{{ importResult.successRecords }}</span>
          </el-descriptions-item>

          <el-descriptions-item label="失败/已录入 记录数">
            <span class="result-number error">{{ importResult.failedRecords }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resultDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="loadHistoryAndClose">查看数据</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { UploadFilled, View } from "@element-plus/icons-vue";
import { deviceTemplateApi } from "@/services/api";

// 响应式数据
const currentStep = ref("main");
const fileList = ref([]);
const importResult = ref(null);
const devices = ref([]);
const commandingUnits = ref([]);
const searchDeviceText = ref("");
const searchCommandingUnit = ref("");
const uploadDialogVisible = ref(false);
const resultDialogVisible = ref(false);
const categoryGroups = computed(() => {
  const groups = new Map();

  // 安全检查
  if (!devices.value || devices.value.length === 0) {
    return [];
  }

  // 分组设备数据 - 只按设备类型分组
  devices.value.forEach((device) => {
    // 遍历每条设备
    if (!device) return; // 安全检查

    // 按设备类型分组
    if (device.deviceCategory) {
      if (!groups.has(device.deviceCategory)) {
        // 如果该设备类型还不存在，创建一个新的数组
        groups.set(device.deviceCategory, []);
      }
      // 将设备添加到对应的设备类型分组中
      groups.get(device.deviceCategory).push(device);
    }
  });

  // 转换为数组并返回
  return Array.from(groups.entries()).map(([category, devices]) => ({
    deviceCategory: category,
    categoryGroup: devices,
    // 其他需要的字段可以在这里添加
  }));
});

// 根据搜索数据，搜索受令单位
const filteredCommandingUnity = computed(() => {
  // 如果没有数据或无搜索词，直接返回原始分组
  if (!commandingUnits.value || commandingUnits.value.length === 0) return [];
  if (!searchCommandingUnit.value) return commandingUnits.value;

  // 对每个受令单位进行过滤
  return commandingUnits.value.filter((commandingUnit) => {
    return (
      commandingUnit &&
      commandingUnit.unitName &&
      commandingUnit.unitName.includes(searchCommandingUnit.value)
    );
  });
});
// 根据搜索数据，搜索设备
const filteredDevices = computed(() => {
  // 如果没有数据或无搜索词，直接返回原始分组
  if (!categoryGroups.value || categoryGroups.value.length === 0) return [];
  if (!searchDeviceText.value) return categoryGroups.value;

  // 对每个设备分类组进行过滤
  return categoryGroups.value
    .map((group) => {
      // 过滤该组内的设备
      const filteredCategoryGroup = group.categoryGroup.filter((device) => {
        return (
          (device &&
            device.deviceName &&
            device.deviceName.includes(searchDeviceText.value)) ||
          (device &&
            device.deviceDoubleCode &&
            device.deviceDoubleCode.includes(searchDeviceText.value)) ||
          (device &&
            device.voltageLevel &&
            device.voltageLevel.includes(searchDeviceText.value)) ||
          (device &&
            device.deviceType &&
            device.deviceType.includes(searchDeviceText.value)) ||
          (device &&
            device.deviceCode &&
            device.deviceCode.includes(searchDeviceText.value))
        );
      });

      // 返回过滤后的分组，保留原结构
      return {
        ...group,
        categoryGroup: filteredCategoryGroup,
      };
    })
    .filter((group) => group.categoryGroup.length > 0); // 过滤掉空组
});

// 是否有历史数据（仅根据设备数据判断）
const hasHistoryData = computed(() => {
  return devices.value.length > 0;
});

// 清空覆写/导入新增
const do_clear = ref(true);

const lastUpdateTime = computed(() => {
  if (devices.value.length === 0) return "暂无数据";
  const latestTime = devices.value.reduce((latest, device) => {
    return new Date(device.updatedTime) > new Date(latest) ? device.updatedTime : latest;
  }, devices.value[0].updatedTime);
  return formatTime(latestTime);
});

// 方法
const handleFileChange = (file: any, uploadFileList: any[]) => {
  fileList.value = uploadFileList;
};

// 显示上传对话框
const showUploadDialog = () => {
  fileList.value = [];
  uploadDialogVisible.value = true;
};

// 上传模板
const uploadTemplate = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning("请先选择文件");
    return;
  }

  try {
    ElMessage.info("开始导入设备模板...");
    const response = await deviceTemplateApi.upload(
      fileList.value[0].raw,
      do_clear.value,
      "设备模板导入"
    );
    importResult.value = response;
    uploadDialogVisible.value = false;
    resultDialogVisible.value = true;
    ElMessage.success("设备模板导入完成");
    // 刷新数据
    try {
      await loadHistoryData();
    } catch (error) {
      ElMessage.error("加载数据失败: " + error.message);
    }
  } catch (error) {
    ElMessage.error("导入失败: " + (error.message || "未知错误"));
  }
};

// 加载历史数据并关闭结果对话框
const loadHistoryAndClose = async () => {
  try {
    await loadHistoryData();
    resultDialogVisible.value = false;
    viewHistoryData();
  } catch (error) {
    ElMessage.error("加载数据失败: " + error.message);
  }
};

// 查看历史数据
const viewHistoryData = async () => {
  try {
    await loadHistoryData();
    currentStep.value = "history";

    // 不显示消息提示，让页面的空状态组件来处理显示
  } catch (error) {
    ElMessage.error("加载历史数据失败: " + error.message);
    // 即使出错也跳转到历史页面，显示无数据提示
    currentStep.value = "history";
  }
};

// 时间格式化
const formatTime = (time: string) => {
  if (!time) return "暂无";
  return new Date(time).toLocaleString("zh-CN");
};

// 查看历史数据
const loadHistoryData = async () => {
  try {
    const [devicesResponse, commandingUnitsResponse] = await Promise.all([
      deviceTemplateApi.getDevices(),
      deviceTemplateApi.getCommandingUnits(),
    ]);
    devices.value = devicesResponse || [];
    commandingUnits.value = commandingUnitsResponse || [];

    console.log(
      `加载了 ${devicesResponse?.length || 0} 条设备数据和 ${
        commandingUnitsResponse?.length || 0
      } 个受令单位`
    );
    console.log(`hasHistoryData: ${devices.value.length > 0}`);
  } catch (error) {
    console.error("加载历史数据失败:", error);
    // 确保即使出错也设置空数组，这样页面能正常显示"无数据"提示
    devices.value = [];
    commandingUnits.value = [];
  }
};

// 页面加载时不自动获取数据，等用户选择操作
onMounted(() => {
  // 不自动加载数据，由用户主动选择
});
</script>

<style scoped>
.device-template {
  padding: 40px 0;
}

.page-header {
  text-align: center;
  margin-bottom: 60px;
}

.page-header h2 {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 15px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
}

.main-card {
  margin-bottom: 40px;
  min-height: 500px;
}

.step-card {
  margin-bottom: 40px;
  min-height: 400px;
}

.step-card .el-card__header h3 {
  margin: 0;
  font-size: 20px;
  color: #2c3e50;
}

.upload-area {
  padding: 40px 0;
}

.upload-dragger {
  width: 100%;
}

.upload-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

.upload-text p {
  margin: 10px 0;
  font-size: 16px;
  color: #606266;
}

.upload-tip {
  font-size: 14px !important;
  color: #909399 !important;
}

.step-actions {
  text-align: center;
  margin-top: 40px;
}

.result-summary {
  margin: 40px 0;
}

.result-number {
  font-size: 18px;
  font-weight: bold;
}

.result-number.success {
  color: #67c23a;
}

.result-number.error {
  color: #f56c6c;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 20px;
  color: #2c3e50;
}

/* 修复表格文字颜色 */
.el-table {
  color: #2c3e50 !important;
}

.el-table td,
.el-table th {
  color: #2c3e50 !important;
}

.el-table .cell {
  color: #2c3e50 !important;
}

/* 表格头部样式 */
.el-table th {
  background-color: #fafafa !important;
  color: #2c3e50 !important;
  font-weight: 600 !important;
}

/* 表格行样式 */
.el-table tr {
  background-color: #ffffff !important;
}

.el-table tr:nth-child(even) {
  background-color: #f8f9fa !important;
}

/* 新增样式 */
.no-data-hint {
  text-align: center;
  padding: 80px 0;
}

.empty-description h4 {
  margin: 16px 0 12px 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
}

.empty-description p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.empty-description .empty-tip {
  color: #909399;
  font-size: 13px;
  margin-top: 16px;
}

.empty-actions {
  margin-top: 24px;
}

.empty-actions .el-button {
  padding: 12px 24px;
  border-radius: 6px;
}

.search-bar {
  margin-bottom: 20px;
}

.history-data {
  margin-top: 30px;
}

.upload-dialog-content .mt-20 {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.data-summary {
  margin: 20px 0;
}

.category-group {
  margin-bottom: 30px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}

/* 确保表格样式统一 */
.device-table {
  margin-bottom: 20px;
  width: 100%;
}

.station-title {
  margin: 0;
  padding: 15px 20px;
  background-color: #f5f7fa;
  color: #2c3e50;
  font-size: 18px;
  border-bottom: 1px solid #e4e7ed;
}

.el-collapse {
  border: none;
  background-color: white !important;
}

.el-collapse-item {
  border-bottom: 1px solid #e4e7ed;
}

.el-collapse-item__header {
  padding: 15px 20px;
  font-size: 16px;
  color: #2c3e50;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
}

.el-collapse-item:last-child {
  border-bottom: none;
}

/* 调整 el-collapse-item 的内容区域 */
.el-collapse-item__wrap {
  padding: 0 20px;
}

.el-tag {
  margin: 2px !important; /* 增加水平间距 */
}
</style>
